#include "WiiCISIOPublicInclude.h"
#include "WiiCISIOPrivateInclude.h"
#include "WiiCISIODevice.h"

#include "WiiCISIORoot.h"

namespace WiiCIS {
	namespace IO {
		Device::Device()
			: rumble(false), leds(0) {
				root = Root::Create();
		}

		Device::~Device() {
			delete root;
		}

		bool Device::isConnected() {
			return root->isConnected();
		}

		void Device::Connect() {
			if (!isConnected())
				root->Connect();
		}

		void Device::Disconnect() {
			if (isConnected())
				root->Disconnect();
		}

		void Device::setRumble(bool value) {
			rumble = value;
			SendData(WMCMD_LED, &leds, 1);
		}

		void Device::setLeds(byte value) {
			leds = value & 0xF0;
			SendData(WMCMD_LED, &leds, 1);
		}

		void Device::setReportType(ReportType reportType) {
			byte data[2] = {0x00, reportType};
			SendData(WMCMD_REPORTTYPE, data, 2);
		}

		byte *Device::Read() {
			byte *buffer = new byte[MAX_PAYLOAD];
			root->Read(buffer);
			return buffer;
		}

		void Device::SendData(CommandType commandType, byte *message, int length) {
			byte buffer[32]; // "QUOTE": No payload is better than this.
			buffer[0] = commandType;

			memcpy(&(buffer[1]), message, length);

			switch (commandType) {
			case WMCMD_LED:
			case WMCMD_RUMBLE:
			case WMCMD_REPORTTYPE:
			case WMCMD_CTRLSTATUS:
			case WMCMD_WRITEDATA:
			case WMCMD_READDATA:
				if (rumble)
					buffer[1] |= 0x01;
			}

			root->Write(buffer, length + 1);
		}
	}
}